/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


//google maps crap
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;
var z = 6;
var googleTypes=[];
var googleTypesRadius = [];   //Roughly one mile in meters


//Mini global variables
var directionsDisplayMini;
var directionsServiceMini = new google.maps.DirectionsService();
var geocoder_mini;
var map_mini;
var newWaypoint;
var waypointPosition;
//This will load the Map when Ready
//GLOBAL 

var startLocation = "";
var endLocation = "";
var wayPoints = [];
var startDate = "";
var endDate = "";
var wayDates = [];// YYYY-MM-DD
var distance = [];
var tripId = -1;
var infoWindow;

//END REGGLOBAL
$(document).ready(function(){
    $("#friendsDropUp").load("./GetFriendsServlet");
    //    init();
    initialize();
    //    initializeMiniMap();
    
    parseIntoList("#locationList");
    parseDatesIntoList("#dateList");
    tripId = parseInt($("#tripId").val(), 10);
    $("#mainDiv").html("Calculating...");
    displayRoute();//CALLS STATS DROP UP INIT
   // wayPointsInit();
    generateSchedule();
    var j = 0;
    
    
    
    
    
    
    
});
function wayPointsInit(){
    
    loadWaypoints();
}
function statsDropUpinit(){
    var numberOfStops = wayPoints.length + 2;
    var totalTime = computeDateDifference(startDate,endDate);
    var dateStart = parseDate(startDate);
    var dateEnd = parseDate(endDate);
    
    var totalDistance  = 0;
    for(var i = 0; i < distance.length; i++){
        totalDistance += distance[i];
    }
    totalDistance = Math.round(totalDistance * 100);
    totalDistance /= 100;
    totalDistance = totalDistance + " Miles";
    $("#mainDiv").html("<br>Start Date: " + dateStart + "<br>End Date: " + dateEnd + "<br>Total Stops: " + numberOfStops + "</br>Total Time on Trip: " + totalTime + "</br>Total Distance Traveled: " + totalDistance);
    $("#bottomDiv").load("./GetFriendsOnTripForMapPage?tripId=" + tripId);
}
function computeDateDifference(first,last){
    //YYYY - MM - DD
    //0123 4 56 7 89
    var Lyear = parseInt(last.substring(0,4),10);
    var Lmon = parseInt(last.substring(5,7),10);
    var Lday = parseInt(last.substring(8),10);
    var Fyear = parseInt(first.substring(0,4),10);
    var Fmon = parseInt(first.substring(5,7),10);
    var Fday = parseInt(first.substring(8),10);
    
    var deltaYear = Lyear - Fyear;
    var deltaMon = Lmon - Fmon;
    var deltaDay = Lday - Fday;
    var str = "";
    if(deltaDay > 0){
        str += deltaDay + " days ";
    }
    if(deltaMon > 0){
        if(deltaDay > 0){
            str += ","
        }
        str += deltaMon + " months "
    }
    if(deltaYear > 0){
        if(deltaMon > 0){
            str += ","
        }
        str += deltaYears + " years";
    }
    if(str == ""){
        return "Same Day Trip";
    }
    return str;
}

function parseDate(date){
    var year = parseInt(date.substring(0,4),10);
    var mon = parseInt(date.substring(5,7),10);
    var day = parseInt(date.substring(8),10);
    var newMonth = "";
    
    switch (mon) {
        case 1:
            newMonth = "January";
            break;
        case 2:
            newMonth = "February";
            break;
        case 3:
            newMonth = "March";
            break;
        case 4:
            newMonth = "April";
            break;
        case 5:
            newMonth = "May";
            break;
        case 6:
            newMonth = "June";
            break;
        case 7:
            newMonth = "July";
            break;
        case 8:
            newMonth = "August";
            break;
        case 9:
            newMonth = "September";
            break;
        case 10:
            newMonth = "October";
            break;
        case 11:
            newMonth = "November";
            break;
        case 12:
            newMonth = "December";
            break;
    }
    
    var str = newMonth + " " + day + ", " + year;
    return str;
}


function fillGoogleTypes(){
    googleTypes[0] = 'airport';
    googleTypes[1] = 'amusement_park';
    googleTypes[2] = 'aquarium';
    googleTypes[3] = 'art_gallery';
    googleTypes[4] = 'atm';
    googleTypes[5] = 'bank';
    googleTypes[6] = 'bar';
    googleTypes[7] = 'campground';
    googleTypes[8] = 'car_rental';
    googleTypes[9] = 'car_repair'
    googleTypes[10] = 'casino';
    googleTypes[11] = 'church';
    googleTypes[12] = 'clothing_store';
    googleTypes[13] = 'food';
    googleTypes[14] = 'gas_station';
    googleTypes[15] = 'grocery_or_supermarket';
    googleTypes[16] = 'hospital';
    googleTypes[17] = 'laundry';
    googleTypes[18] = 'lawyer';
    googleTypes[20] = 'lodging';
    googleTypes[21] = 'meal_takeaway';
    googleTypes[22] = 'movie_theater';
    googleTypes[23] = 'moving_company';
    googleTypes[24] = 'museum';
    googleTypes[25] = 'parking';
    googleTypes[26] = 'pharmacy';
    googleTypes[27] = 'zoo';
}
function fillGoogleTypesRadius(){
    googleTypesRadius[0] = 1610;    //1
    googleTypesRadius[1] = 1610*5;    //5
    googleTypesRadius[2] = 1610*10;    //10
    googleTypesRadius[3] = 1610*20;    //20
    googleTypesRadius[4] = 1610*50;    //50,100
    googleTypesRadius[5] = 1610*100;    //100
    
    
}


function parseIntoList(tagId){
    wayPoints = [];
    var str =   $(tagId).val();
    // str = str.substring(1,str.length-1);
    // alert(str);
    startLocation = str.substring(0, str.indexOf("|")).trim();
    str = str.substring(str.indexOf("|")+1);
    //WAY POINTS
    while(str.indexOf("|") != -1){
        var s = str.substring(0,str.indexOf("|"));
        wayPoints.push(s.trim());
        str = str.substring(str.indexOf("|")+1);
    }
    endLocation = str.trim();
//  alert("Start Location: " + startLocation);
//  alert("End Location: " + endLocation);
//  alert("Waypoints: " + wayPoints);
}
function parseDatesIntoList(tagId){
    wayDates = [];
    var str = $(tagId).val();
    startDate = str.substring(0, str.indexOf("|")).trim();
    str = str.substring(str.indexOf("|")+1);
    //WAY POINTS
    while(str.indexOf("|") != -1){
        var s = str.substring(0,str.indexOf("|"));
        wayDates.push(s.trim());
        str = str.substring(str.indexOf("|")+1);
    }
    endDate = str.trim();
// alert("START DATE: " +  startDate);
// alert("END DATE: " + endDate);
}
////////////
function displayRoute(){
    var waypts = [];
    // Here we are going to read through all the waypoint 'classes'
    var start = startLocation;
    var end = endLocation;
    if(wayPoints.length <= 8){
        for (var i = 0; i < wayPoints.length; i++) {
            if (wayPoints[i] != "") {
                waypts.push({
                    location:wayPoints[i],
                    stopover:true
                });
            }
        }

        var request = {
            origin: start,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: false,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                var route = response.routes[0];
                // var summaryPanel = document.getElementById('directions_panel');
                // summaryPanel.innerHTML = '';
                // For each route, display summary information.
                distance = [];
                for (var i = 0; i < route.legs.length; i++) {
                    distance[i] = route.legs[i].distance.value * .00062137;
                }
                statsDropUpinit();
            }
        });
    }
    else{
        displayLongRoute();
    }
}
function displayLongRoute(){
    var tempWays = [[]];
    var wayPointsT = [];
    var x = 0;
    var index = 0;
    //BUILD ROUTES
    wayPointsT.push(startLocation);
    for(var i = 0; i < wayPoints.length; i++){
        wayPointsT.push(wayPoints[i]);
    }
    wayPointsT.push(endLocation);
    for(var i = 0; i < wayPointsT.length;i++){
        tempWays[index][x++] = wayPointsT[i];
        if(i != 0 && i % 8 == 0){
            index++;
            x = 0;
        }
    }
    for(var i = 0; i < tempWays.length; i++){
        var waypts = [];
        // Here we are going to read through all the waypoint 'classes'
        var start = tempWays[i][0];
        var end = tempWays[i][tempWays[i].length-1];
        for (var x = 1; x < tempWays[i].length-1; x++) {
            if (tempWays[i][x] != "") {
                waypts.push({
                    location:tempWays[i][x],
                    stopover:true
                });
            }
        }

        var request = {
            origin: start,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: false,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    }
}

function addToWayPtList(location, date)
{
    // alert("ADDING: " + location + " | "+ date);
    var tempList = [];
    var tempLocList = [];
    var index = -1;
    for(var i = 0; i < wayDates.length; i++)
    {
        if(checkDate(wayDates[i],date) > 0){
            //THIS IS THE INDEX
            index = i;
            // alert(index);
            break;
        }
    }
    if(wayDates.length != 1 && index != -1){
        for(var n = 0; n < index; n++){
            tempList[n] = wayDates[n]
            tempLocList[n] = wayPoints[n];
        }
        tempList[index] = date;
        tempLocList[index] = location;
        for(var m = index; m < wayDates.length; m++){
            tempList[m+1] = wayDates[m]
            tempLocList[m+1] = wayPoints[m];
        }
    }
    else{
        if(index == -1){
            index = wayPoints.length;
            // alert(index);
            wayPoints[index] = location;
            wayDates[index] = date;
            tempList = wayDates;
            tempLocList = wayPoints;
            
        }
        else{
            tempList[0] = date;
            tempLocList[0] = location;
            index = 0;
            tempList[1] = wayDates[0];
            tempLocList[1] = wayPoints[0];
        }
    // alert("THIS");
    }
    wayDates = tempList;
    wayPoints = tempLocList;
    return index;
}

function codeAddressStartEnd(tagId) { 
   
    var startIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
    var endIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    
    var marker;
    var address = document.getElementById(tagId).value;
    geocoder_mini.geocode( {
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map_mini.setCenter(results[0].geometry.location);    
            marker = new google.maps.Marker({
                map: map_mini,
                position: results[0].geometry.location
            });
            
            marker.setIcon(startIconFile);
            startMarker.push(marker);
            //            $("#" + tagId).val(results[0].formatted_address); 
            newWaypoint = results[0].formatted_address;
            newWayDate = $('#dateTextBox'.val());
            waypointPosition = addToWayPtList(newWaypoint, newWayDate);
        //            $("#startSpan").html("Start: <span class='sizeEighteen'> " + startLocation + "</span> Date: <span class='sizeEighteen'>" + startDate + "</span>");
        //            $("#addStart").attr("value","Update");  
            
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
       
    });
}

jQuery(function() {
    jQuery( "#dateTextBox" ).datepicker();
});

$("#addAWaypointButton").click(addWaypoint());
function addWaypoint(){
    
    
    var locations = startLocation + "|";
    for(var i = 0; i < wayPoints.length; i++){
        locations += wayPoints[i] + "|";
    }
    locations += endLocation;
    var dates = "";//FILL THIS IN
    dates += startDate + "|";
    for(var i = 0; i < wayDates.length; i++){
        dates += wayDates[i] + "|";
    }
    dates += endDate;
    location.href = "./AddWaypointServlet?tripid=" + tripId + "&locations=" + locations + "&dates=" + dates + "&position=" + waypointPosition + "&newWaypoint=" + newWaypoint + "&newWaypointDate=" + newWayDate;
}

function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
        }
    }
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });
    
    google.maps.event.addListener(marker, 'click', function() {
        var html = "<a href='https://www.google.com/?q=" + place.name + "' target='_blank'>" + place.name + "</a>";
        
//        var html = place.name;
        infowindow.setContent(html);
        infowindow.open(map, this);
    });
}

function initialize(){
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var mapOptions = {
        zoom: z,
        chicago: new google.maps.LatLng(-28.643387, 153.612224),
        //      center: chicago,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            position: google.maps.ControlPosition.LEFT_TOP   
        },
        panControl: false,
        panControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.RIGHT_CENTER
        },
        scaleControl: true,
        scaleControlOptions: {
            position: google.maps.ControlPosition.TOP_LEFT
        },
        streetViewControl: true,
        streetViewControlOptions: {
            position: google.maps.ControlPosition.RIGHT_CENTER
        }
    }
    
    //    var miniMapOptions = {
    //        zoom: 6,
    //        mapTypeId: google.maps.MapTypeId.ROADMAP,
    //        center:chicago
    //    }
   

    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap(map);
//    map_mini = new google.maps.Map(document.getElementById('map_miniDiv'), miniMapOptions);
//    map_mini.checkResize();
}
    
    
//$("#locationFindButton").on("click", function(){
function performClick(){
    codeAddress("locationFindBar");
}

function codeAddress(tagId) {
    
    //var greenIcon = new GIcon(G_DEFAULT_ICON);
   
   
var startIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
//    var endIconFile = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
var coord = 0;
var marker;
var address = document.getElementById(tagId).value;
geocoder.geocode( {
    'address': address
}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);    
        marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
        marker.setIcon(startIconFile);
        coord = results[0].geometry.location;
        //                alert(coord);
//        alert(coord);
        //    var place = codeAddress("locationFindBar");
        fillGoogleTypes();
        fillGoogleTypesRadius();
//        alert(googleTypes[$('#locationTypeSelectBox').val()]);
//        alert(googleTypesRadius[$('#radiusSelectBox').val()]);
        var request = {
            //location: codeAddressWay(locationsBar),
            location: coord,
            radius: googleTypesRadius[$('#radiusSelectBox').val()],
            types: [googleTypes[$('#locationTypeSelectBox').val()]]
        };
        
        z = 10;
        
        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(request, callback);
    } 
    else {
        alert('Geocode was not successful for the following reason: ' + status);
    }       
});

}

function init(){
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
    zoom: z,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    center:chicago
}
}
////// FIND FRIENDS //////
function addFriend(friend_id){
    $("#friendsDropUp").load("./FindFriendServlet?id=" + friend_id);   
}
function addFriendsToTrip(){
    var friends = [];
    var x = 0;
    $("input:checkbox[name=friendCheckbox]:checked").each(function(){
        friends[x] = $(this).val(); 
        x += 1;
    });
    var frs = "";
    for(var k = 0; k < friends.length; k++){
        frs += "&friends=" + friends[k];
    }
    $("#botfriendsPanel").load("./AddFriendsToTripServlet?tripId=" + selectedTrip + frs);
    $("input:checkbox[name=friendCheckbox]:checked").each(function(){
        $(this).removeAttr("checked"); 
    });
}

function deleteFriend(){
    var friends = [];
    var x = 0;
    $("input:checkbox[name=friendCheckbox]:checked").each(function(){
        friends[x] = $(this).val(); 
        x += 1;
    });
    var frs = "";
    for(var k = 0; k < friends.length; k++){
        frs += "&friends=" + friends[k];
    }
    $("#friendsBar").load("./DeleteFriendServlet?" + frs);
    $("input:checkbox[name=friendCheckbox]:checked").each(function(){
        $(this).removeAttr("checked"); 
    });   
}

//Sample call
//$("#startButton").click(function(){
//  codeAddress("start");
//});
//Code for getting the address and updating the map
/*function init(){
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var mapOptions = {
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.SATELLITE,
        center:chicago
    }
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap(map);
    map_mini = new google.maps.Map(document.getElementById("map_2"),mapOptions);
    map_mini.checkResize();
}*/
var markers = []